package com.mediastory.spsserver.system.auth;

import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mediastory.spsserver.users.domain.Users;
import com.mediastory.spsserver.users.service.UsersSvc;

/**
 * @author Jaewon Choi
 *
 */

@Service("userAuthService")
@Transactional(readOnly = true)
public class UserAuthSvc implements UserDetailsService {

	@Autowired
    private UsersSvc usersSvc;

	@Override
	public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {

		User user = null;
		try {
			Users authUser = usersSvc.findbyAuth(id);

			boolean enabled = true;
			if(authUser.getEnabled() != null && authUser.getEnabled() == 0){
				enabled = false;
			}
			
			boolean usersNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean usersNonLocked = true;
			
			Vector<GrantedAuthority> authorities = new Vector<GrantedAuthority>();
			authorities.add(new  SimpleGrantedAuthority(authUser.getAuthority()));
			String password = authUser.getPassword();
			user = new User(id, password, enabled, usersNonExpired, credentialsNonExpired, usersNonLocked, authorities);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		return user;
	}
	
}